package com.xintool.window.Buttons;

import com.xintool.mapper.PetsList;

import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;

public class Button_jltj extends ButtonFactory {

    private static JFrame tjFrame;
    private static JTextField inputField; // 输入框组件

    @Override
    public JButton showButton() {
        JButton button_jltj = ButtonFactory.getButton("精灵图鉴");
        button_jltj.addActionListener(e -> createMainWindow());
        return button_jltj;
    }

    public void createMainWindow() {
        // 单例窗口检查
        if (tjFrame != null && tjFrame.isDisplayable()) {
            tjFrame.toFront();
            return;
        }

        // 窗口初始化
        tjFrame = new JFrame("精灵图鉴查询");
        tjFrame.setSize(240, 80); // 调整更适合输入框的高度
        tjFrame.setResizable(false);
        tjFrame.setLocationRelativeTo(null);
        tjFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // 添加主内容面板
        tjFrame.add(createMainPanel());

        // 窗口关闭监听
        tjFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                tjFrame = null;
            }
        });

        tjFrame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // 输入区域面板
        JPanel inputPanel = new JPanel(new BorderLayout(10, 10));
        inputField = new JTextField();

        // 添加回车监听（新增代码）
        inputField.addActionListener(this::handleQuery);
        inputPanel.add(new JLabel("精灵ID/名称:"), BorderLayout.WEST);
        inputPanel.add(inputField, BorderLayout.CENTER);

        // 查询按钮
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(this::handleQuery);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(queryButton);

        // 组装主面板
        panel.add(inputPanel,BorderLayout.CENTER);
        panel.add(buttonPanel,BorderLayout.EAST);

        return panel;
    }

    private void handleQuery(ActionEvent e) {
        String input = inputField.getText().trim();
        if (input.isEmpty()) {
            JOptionPane.showMessageDialog(tjFrame, "请输入ID或精灵名称");
            return;
        }

        // 判断输入类型
        if (input.matches("\\d+")) {
            handleNumericInput(Integer.parseInt(input));
        } else {
            handleStringInput(input);
        }
    }

    private void handleNumericInput(int id) {
        // 在PetsList中查找
        if (id < 1 || id > PetsList.PETSLIST.length) {
            JOptionPane.showMessageDialog(tjFrame, "暂支持查询ID范围：1-500");
            return;
        }

        // 解析格式："1.布布种子" -> "布布种子"
        String fullName = PetsList.PETSLIST[id - 1];
        String petName = fullName.split("\\.", 2)[1].trim();
        openWikiPage(petName);
    }

    private void handleStringInput(String input) {
        // 直接使用输入内容
        openWikiPage(input);
    }

    private void openWikiPage(String petName) {
        try {
            // 构建URL（处理特殊字符）
            String encodedName = petName.replace(" ", "_");
            URI uri = new URI("https://seer.fandom.com/zh/wiki/" + encodedName);

            // 跨平台打开浏览器
            if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                if (desktop.isSupported(Desktop.Action.BROWSE)) {
                    desktop.browse(uri);
                } else {
                    throw new Exception("浏览器不支持");
                }
            } else {
                throw new Exception("桌面操作不支持");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(tjFrame,
                    "打开页面失败: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE
            );
            ex.printStackTrace();
        }
    }
}